import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By


class MouseOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()

    # 单击
    def click(self):
        # 第一种
        self.driver.get('https://sahitest.com/demo/clicks.htm')
        time.sleep(3)
        ele = self.driver.find_element(By.XPATH, '//form[@name="f1"]/input[3]')
        ele.click()

        # 第二种(用鼠标方法)
        ac = ActionChains(self.driver)
        ac.click(ele).perform()

    # 右击
    def context_click(self):
        time.sleep(3)
        self.driver.get('https://sahitest.com/demo/clicks.htm')
        ele = self.driver.find_element(By.XPATH, '//form[@name="f1"]/input[4]')
        ac = ActionChains(self.driver)
        ac.context_click(ele).perform()

    # 双击
    def double_click(self):
        time.sleep(3)
        self.driver.get('https://sahitest.com/demo/clicks.htm')
        ele = self.driver.find_element(By.XPATH, '//form[@name="f1"]/input[2]')
        ac = ActionChains(self.driver)
        ac.double_click(ele).perform()

    # 拖动
    def drag_and_drop(self):
        self.driver.get('https://sahitest.com/demo/dragDropMooTools.htm')
        time.sleep(3)
        source = self.driver.find_element(By.ID, 'dragger')
        target = self.driver.find_element(By.XPATH, '//div[4]')
        ac = ActionChains(self.driver)
        ac.drag_and_drop(source, target).perform()

    # 悬停
    def move_to_element(self):
        self.driver.get('https://sahitest.com/demo/mouseover.htm')
        time.sleep(3)
        ele = self.driver.find_element(By.XPATH, '//div/div')
        ac = ActionChains(self.driver)
        ac.move_to_element(ele).perform()

    # 关闭
    def quit(self):
        time.sleep(3)
        self.driver.quit()


# 调用
if __name__ == '__main__':
    mo = MouseOperation()
    mo.click()
    mo.context_click()
    mo.double_click()
    mo.drag_and_drop()
    mo.move_to_element()

    mo.quit()
